package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DishDeleteException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlovorMapper dishFlovorMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;



    @Override
    @Transactional
    @CacheEvict(cacheNames = "dishListCache",key = "#dishDTO.categoryId")
    public void save(DishDTO dishDTO) {
        //新增时 需要删除这个菜品的分类菜品缓存
//        String key = "dish_" + dishDTO.getCategoryId();
//        cleanCache(key);

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //保存菜品
        dishMapper.save(dish);
        //保存口味
        List<DishFlavor> flavors = dishDTO.getFlavors().stream().map(item -> {
            DishFlavor dishFlavor = new DishFlavor();
            BeanUtils.copyProperties(item, dishFlavor);
            dishFlavor.setDishId(dish.getId());
            return dishFlavor;
        }).collect(Collectors.toList());
        dishFlovorMapper.saveBatch(flavors);
    }


    private void cleanCache(String key) {
        Set<String> keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<Dish> page = dishMapper.pageQuery(dishPageQueryDTO);
        List<DishVO> dishVOList = page.getResult().stream().map(item -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(item, dishVO);
            Category category = categoryMapper.getById(item.getCategoryId());
            dishVO.setCategoryName(category.getName());
            List<DishFlavor> dishFlavors = dishFlovorMapper.selectByDishId(item.getId());
            dishVO.setFlavors(dishFlavors);
            return dishVO;
        }).collect(Collectors.toList());
        return new PageResult(page.getTotal(),dishVOList);
    }

    @Override
    @Transactional
    @CacheEvict(cacheNames = "dishListCache",allEntries = true)
    public void deleteBatch(List<Long> ids) {
        //考虑到如果再去查分类的话 还是需要频繁的查询数据库 所以直接将缓存删掉就行
//        String key = "dish_*";
//        cleanCache(key);

        if(ids == null || ids.size() == 0){
            return;
        }
        for (Long id : ids) {
            //不能删除起售中的菜品
            Dish dish = dishMapper.getById(id);
            if(StatusConstant.ENABLE.equals(dish.getStatus())){
                throw new DishDeleteException(MessageConstant.DISH_ON_SALE);
            }
        }
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        //当前菜品有关联套餐 不能删除
        if(setmealIds != null && setmealIds.size() > 0){
            throw new DishDeleteException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品
        dishMapper.deleteBatch(ids);
        //删除菜品关联的口味
        dishFlovorMapper.deleteByDishIds(ids);
    }

    @Override
    public DishVO getById(Long id) {
        Dish dish = dishMapper.getById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        List<DishFlavor> dishFlavors = dishFlovorMapper.selectByDishId(id);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    @Override
    @Transactional
    @CacheEvict(cacheNames = "dishListCache",key = "#dishDTO.categoryId")
    public void update(DishDTO dishDTO) {
//        String key = "dish_" + dishDTO.getCategoryId();
//        cleanCache(key);

        //修改菜品
        dishMapper.update(dishDTO);
        //修改口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //删除原先的
        dishFlovorMapper.deleteByDishIds(Arrays.asList(dishDTO.getId()));
        flavors = flavors.stream().map(item -> {
            item.setDishId(dishDTO.getId());
            return item;
        }).collect(Collectors.toList());
        //重新添加口味
        dishFlovorMapper.saveBatch(flavors);
    }

    @Override
    @CacheEvict(cacheNames = "dishListCache",allEntries = true)
    public void updateStatus(Long id, Integer status) {
        DishDTO dishDTO = new DishDTO();
        dishDTO.setId(id);
        dishDTO.setStatus(status);
        dishMapper.update(dishDTO);
    }

    @Override
    public List<Dish> getDishListByCategoryId(Long categoryId) {
        List<Dish> dishes = dishMapper.getDishListByCategoryId(categoryId);
        return dishes;
    }

    @Override
    @Cacheable(cacheNames = "dishListCache",key = "#dish.categoryId")
    public List<DishVO> listWithFlavor(Dish dish) {

//        String key = "dish_" + dish.getCategoryId();
//        String json = redisTemplate.opsForValue().get(key);
//        List<DishVO> dishVOS = JSON.parseObject(json, new TypeReference<List<DishVO>>() {
//        });
//        if (dishVOS != null && dishVOS.size() >0) {
//            return dishVOS;
//        }


        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlovorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        //redisTemplate.opsForValue().set(key,JSON.toJSONString(dishVOList));
        return dishVOList;
    }


}
